<template>
  <div class="team-sprint">
    <div class="header">
      <h2>学习小组</h2>
      <div class="header-right">
        <el-input
          v-model="searchText"
          placeholder="搜索小组"
          class="search-input"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-radio-group v-model="filterType" size="small">
          <el-radio-button label="all">全部小组</el-radio-button>
          <el-radio-button label="mine">我创建的</el-radio-button>
          <el-radio-button label="joined">已加入的</el-radio-button>
        </el-radio-group>
        <el-button type="primary" @click="openCreateDialog">
          创建小组
        </el-button>
      </div>
    </div>

    <!-- 团队列表 -->
    <el-row :gutter="20" class="team-list">
      <el-col 
        v-for="team in filteredTeams" 
        :key="team.id" 
        :xs="24" 
        :sm="12" 
        :md="8" 
        :lg="6"
      >
        <el-card shadow="hover" class="team-card">
          <template #header>
            <div class="card-header">
              <div class="user-info">
                <el-avatar :src="generateAvatar(team.creator_name)" />
                <span class="username">{{ team.creator_name }}</span>
              </div>
              <el-tag size="small" :type="team.status === 'active' ? 'success' : 'info'">
                {{ team.status === 'active' ? '进行中' : '已结束' }}
              </el-tag>
            </div>
          </template>
          <div class="team-info">
            <h3 class="team-name">{{ team.name }}</h3>
            <p class="description">{{ team.description }}</p>
            
            <!-- 团队统计信息 -->
            <div class="team-stats">
              <div class="stat-item">
                <span class="stat-label">总学习时长</span>
                <span class="stat-value">{{ formatSeconds(team.total_seconds || 0) }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">完成任务</span>
                <span class="stat-value">{{ team.completed_tasks || 0 }} 个</span>
              </div>
            </div>

            <div class="meta">
              <span>成员: {{ team.member_count }}/{{ team.max_members }}</span>
              <span>{{ team.start_date }} ~ {{ team.end_date }}</span>
            </div>
            <div class="tags">
              <el-tag size="small">{{ getCategoryText(team.category) }}</el-tag>
              <el-tag size="small" type="warning">{{ getLevelText(team.level) }}</el-tag>
            </div>
            
            <!-- 成员列表（显示贡献时长） -->
            <div class="members-list">
              <div class="members-avatars">
                <el-avatar-group :size="32" :max="3">
                  <el-tooltip 
                    v-for="member in team.members" 
                    :key="member.id"
                    placement="top"
                  >
                    <template #content>
                      <div>
                        <div>{{ member.username }}</div>
                        <div>贡献: {{ member.contribution_formatted || '00:00:00' }}</div>
                      </div>
                    </template>
                    <el-avatar 
                      :src="member.avatar" 
                      :size="32"
                    />
                  </el-tooltip>
                </el-avatar-group>
              </div>
              <span class="member-count">{{ team.member_count }}/{{ team.max_members }}</span>
            </div>

            <!-- 成员贡献排行（简化版） -->
            <div v-if="team.members && team.members.length > 0" class="mini-ranking">
              <div class="ranking-title">贡献排行</div>
              <div 
                v-for="(member, index) in getTopMembers(team.members)" 
                :key="member.id" 
                class="ranking-item"
              >
                <span class="rank">{{ index + 1 }}</span>
                <span class="name">{{ member.username }}</span>
                <span class="contribution">{{ member.contribution_formatted || '00:00:00' }}</span>
              </div>
            </div>

            <div class="actions">
              <template v-if="isTeamCreator(team)">
                <el-button type="primary" text @click="openEditDialog(team)">编辑</el-button>
                <router-link :to="`/team/${team.id}`">
                  <el-button type="primary" text>管理</el-button>
                </router-link>
              </template>
              <template v-else-if="isTeamMember(team)">
                <el-button type="danger" text @click="leaveTeam(team)">退出</el-button>
                <router-link :to="`/team/${team.id}`">
                  <el-button type="primary" text>查看</el-button>
                </router-link>
              </template>
              <template v-else>
                <el-button 
                  type="primary" 
                  text 
                  @click="joinTeam(team)"
                  :disabled="team.member_count >= team.max_members"
                >
                  {{ team.member_count >= team.max_members ? '已满员' : '加入' }}
                </el-button>
              </template>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 创建/编辑小组对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑学习小组' : '创建学习小组'"
      width="50%"
      :before-close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="teamForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="小组名称" prop="name">
          <el-input v-model="teamForm.name" />
        </el-form-item>
        
        <el-form-item label="小组描述" prop="description">
          <el-input
            v-model="teamForm.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        
        <el-form-item label="学习目标" prop="goal">
          <el-input
            v-model="teamForm.goal"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
        
        <el-form-item label="开始日期" prop="start_date">
          <el-date-picker
            v-model="teamForm.start_date"
            type="date"
            placeholder="选择开始日期"
          />
        </el-form-item>
        
        <el-form-item label="结束日期" prop="end_date">
          <el-date-picker
            v-model="teamForm.end_date"
            type="date"
            placeholder="选择结束日期"
          />
        </el-form-item>
        
        <el-form-item label="最大人数" prop="max_members">
          <el-input-number
            v-model="teamForm.max_members"
            :min="2"
            :max="10"
          />
        </el-form-item>
        
        <el-form-item label="小组类型" prop="category">
          <el-select v-model="teamForm.category" placeholder="选择小组类型">
            <el-option
              v-for="option in categoryOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="难度级别" prop="level">
          <el-select v-model="teamForm.level" placeholder="选择难度级别">
            <el-option
              v-for="option in levelOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createTeam">
            {{ isEditing ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { teamApi, teamUtils } from '@/api/team'
import { Search } from '@element-plus/icons-vue'

// 基础数据和状态
const currentUserId = ref(localStorage.getItem('userId'))
const filterType = ref('all')
const searchText = ref('')
const loading = ref(false)
const teams = ref([])

// 表单相关
const formRef = ref(null)
const dialogVisible = ref(false)
const isEditing = ref(false)
const currentTeam = ref(null)

// 表单数据
const teamForm = ref({
  name: '',
  description: '',
  goal: '',
  start_date: '',
  end_date: '',
  max_members: 5,
  category: 'study',
  level: 'beginner'
})

// 分类选项
const categoryOptions = [
  { label: '学习小组', value: 'study' },
  { label: '项目小组', value: 'project' },
  { label: '兴趣小组', value: 'interest' }
]

// 级别选项
const levelOptions = [
  { label: '初级', value: 'beginner' },
  { label: '中级', value: 'intermediate' },
  { label: '高级', value: 'advanced' }
]

// 获取团队列表
const fetchTeams = async () => {
  loading.value = true
  try {
    const params = {
      search: searchText.value,
      filter_type: filterType.value,
      user_id: currentUserId.value
    }
    const response = await teamApi.getTeams(params)
    teams.value = response
  } catch (error) {
    console.error('获取团队列表失败:', error)
    ElMessage.error('获取团队列表失败')
  } finally {
    loading.value = false
  }
}

// 监听过滤条件变化
watch([filterType, searchText], () => {
  fetchTeams()
})

// 工具函数
const generateAvatar = (username) => {
  if (!username) return ''
  return `https://api.dicebear.com/7.x/avataaars/svg?seed=${username}`
}

const formatSeconds = (seconds) => teamUtils.formatDuration(seconds)

const getCategoryText = (category) => {
  const map = { study: '学习小组', project: '项目小组', interest: '兴趣小组' }
  return map[category] || category
}

const getLevelText = (level) => {
  const map = { beginner: '初级', intermediate: '中级', advanced: '高级' }
  return map[level] || level
}

const getTopMembers = (members) => {
  if (!members) return []
  return members
    .sort((a, b) => (b.contribution_seconds || 0) - (a.contribution_seconds || 0))
    .slice(0, 3)
}

// 其余方法保持不变...
const openCreateDialog = () => {
  isEditing.value = false
  currentTeam.value = null
  teamForm.value = {
    name: '',
    description: '',
    goal: '',
    start_date: '',
    end_date: '',
    max_members: 5,
    category: 'study',
    level: 'beginner'
  }
  dialogVisible.value = true
}

const openEditDialog = (team) => {
  isEditing.value = true
  currentTeam.value = team
  teamForm.value = {
    name: team.name,
    description: team.description,
    goal: team.goal,
    start_date: new Date(team.start_date),
    end_date: new Date(team.end_date),
    max_members: team.max_members,
    category: team.category,
    level: team.level
  }
  dialogVisible.value = true
}

const rules = {
  name: [
    { required: true, message: '请输入小组名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入小组描述', trigger: 'blur' }
  ],
  goal: [
    { required: true, message: '请输入学习目标', trigger: 'blur' }
  ],
  start_date: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  end_date: [
    { required: true, message: '请选择结束日期', trigger: 'change' }
  ]
}

const formatDate = (date) => {
  if (!date) return ''
  return date.toISOString().split('T')[0]
}

const createTeam = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    const data = {
      ...teamForm.value,
      creator: parseInt(localStorage.getItem('userId')),
      start_date: formatDate(teamForm.value.start_date),
      end_date: formatDate(teamForm.value.end_date)
    }
    
    if (isEditing.value) {
      await teamApi.updateTeam(currentTeam.value.id, data)
      ElMessage.success('更新成功')
    } else {
      await teamApi.createTeam(data)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    formRef.value.resetFields()
    await fetchTeams()
  } catch (error) {
    if (error.response?.data) {
      const errorMsg = error.response.data.error ? 
        Object.values(error.response.data.error).flat().join(', ') :
        (isEditing.value ? '更新失败' : '创建失败')
      ElMessage.error(errorMsg)
    } else {
      console.error(isEditing.value ? '更新失败:' : '创建失败:', error)
      ElMessage.error(isEditing.value ? '更新失败' : '创建失败')
    }
  }
}

const handleClose = (done) => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  isEditing.value = false
  currentTeam.value = null
  teamForm.value = {
    name: '',
    description: '',
    goal: '',
    start_date: '',
    end_date: '',
    max_members: 5,
    category: 'study',
    level: 'beginner'
  }
  done()
}

onMounted(() => {
  fetchTeams()
})

const filteredTeams = computed(() => {
  let result = teams.value

  if (searchText.value) {
    result = result.filter(team => 
      team.name.toLowerCase().includes(searchText.value.toLowerCase()) ||
      team.description.toLowerCase().includes(searchText.value.toLowerCase())
    )
  }

  return result
})

const isTeamMember = (team) => {
  return team.is_member === true
}

const isTeamCreator = (team) => {
  return team.is_creator === true
}

const joinTeam = async (team) => {
  try {
    await teamApi.joinTeam(team.id)
    ElMessage.success('加入成功')
    await fetchTeams()
  } catch (error) {
    console.error('加入失败:', error)
    if (error.response?.data?.error === '已经是团队成员') {
      ElMessage.warning('您已经是团队成员')
      await fetchTeams()
    } else {
      ElMessage.error(error.response?.data?.error || '加入失败')
    }
  }
}

const leaveTeam = async (team) => {
  try {
    await teamApi.leaveTeam(team.id)
    ElMessage.success('退出成功')
    await fetchTeams()
  } catch (error) {
    console.error('退出失败:', error)
    ElMessage.error(error.response?.data?.error || '退出失败')
  }
}
</script>

<style scoped>
.team-sprint {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.team-list {
  margin-top: 20px;
}

.team-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.team-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.description {
  color: var(--el-text-color-regular);
  margin: 0;
}

.team-stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
  padding: 12px;
  background: var(--el-fill-color-lighter);
  border-radius: 6px;
  margin: 8px 0;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-label {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.stat-value {
  font-size: 14px;
  font-weight: 500;
  color: var(--el-color-primary);
}

.meta {
  display: flex;
  justify-content: space-between;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.members-list {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.members-avatars {
  flex: 1;
}

.member-count {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.mini-ranking {
  background: var(--el-fill-color-lighter);
  border-radius: 6px;
  padding: 8px;
}

.ranking-title {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-bottom: 8px;
}

.ranking-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
  font-size: 12px;
}

.rank {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: var(--el-color-primary);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
}

.name {
  flex: 1;
  color: var(--el-text-color-primary);
}

.contribution {
  color: var(--el-text-color-secondary);
}

.actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.username {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.header-right {
  display: flex;
  gap: 16px;
  align-items: center;
}

.search-input {
  width: 200px;
}

.team-name {
  margin: 0 0 8px 0;
  font-size: 16px;
}

.tags {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

:deep(.el-avatar-group .el-avatar) {
  border: 2px solid var(--el-bg-color);
}
</style>